"""
搜索统计和热门航线相关视图
"""
from django.db.models import Count, Q, F
from django.utils import timezone
from django.contrib.auth import get_user_model
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework import status
from datetime import datetime, timedelta
from .models import VesselSchedule, RouteSearchLog, PopularRoute

User = get_user_model()


def get_client_ip(request):
    """获取客户端IP地址"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


def get_port_name(port_code):
    """根据港口代码获取港口名称"""
    try:
        # 简单的港口名称映射，后续可以改进
        port_names = {
            'CNSHK': '蛇口',
            'INMAA': '金奈',
            'CNDCB': '大铲湾',
            'SGSIN': '新加坡',
            'CNYTN': '盐田',
            'IDJKT': '雅加达',
            'VNHPH': '海防',
            'CNNAN': '广州南沙',
            'THBKK': '曼谷',
            'VNSGN': '胡志明'
        }
        return port_names.get(port_code, port_code)
    except:
        return port_code


@api_view(['POST'])
@permission_classes([AllowAny])  # 允许匿名用户记录搜索
def log_route_search(request):
    """
    记录航线搜索日志
    在用户搜索船期时调用此接口记录搜索行为
    """
    try:
        pol_cd = request.data.get('polCd')
        pod_cd = request.data.get('podCd')
        results_count = request.data.get('results_count', 0)
        
        if not pol_cd or not pod_cd:
            return Response({
                'success': False,
                'message': '缺少必要参数：polCd 和 podCd',
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 记录搜索日志
        search_log = RouteSearchLog.objects.create(
            user=request.user if request.user.is_authenticated else None,
            pol_cd=pol_cd,
            pod_cd=pod_cd,
            ip_address=get_client_ip(request),
            user_agent=request.META.get('HTTP_USER_AGENT', ''),
            results_count=results_count
        )
        
        # 异步更新热门航线统计（可以考虑使用Celery）
        update_popular_routes(pol_cd, pod_cd)
        
        return Response({
            'success': True,
            'message': '搜索日志记录成功',
            'data': {
                'log_id': search_log.id
            }
        })
        
    except Exception as e:
        return Response({
            'success': False,
            'message': f'记录搜索日志失败: {str(e)}',
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


def update_popular_routes(pol_cd, pod_cd):
    """
    更新热门航线统计
    每次搜索后调用，更新或创建热门航线记录
    """
    try:
        # 获取或创建热门航线记录
        route_name = f"{get_port_name(pol_cd)} → {get_port_name(pod_cd)}"
        
        popular_route, created = PopularRoute.objects.get_or_create(
            pol_cd=pol_cd,
            pod_cd=pod_cd,
            defaults={
                'route_name': route_name,
                'search_count': 0,
                'search_count_7d': 0,
                'search_count_30d': 0,
                'unique_users_count': 0,
                'popularity_score': 0.0
            }
        )
        
        # 计算各时间段的搜索次数
        now = timezone.now()
        seven_days_ago = now - timedelta(days=7)
        thirty_days_ago = now - timedelta(days=30)
        
        # 总搜索次数
        total_searches = RouteSearchLog.objects.filter(
            pol_cd=pol_cd,
            pod_cd=pod_cd
        ).count()
        
        # 7天内搜索次数
        searches_7d = RouteSearchLog.objects.filter(
            pol_cd=pol_cd,
            pod_cd=pod_cd,
            search_time__gte=seven_days_ago
        ).count()
        
        # 30天内搜索次数
        searches_30d = RouteSearchLog.objects.filter(
            pol_cd=pol_cd,
            pod_cd=pod_cd,
            search_time__gte=thirty_days_ago
        ).count()
        
        # 唯一用户数（包含匿名用户）
        unique_users = RouteSearchLog.objects.filter(
            pol_cd=pol_cd,
            pod_cd=pod_cd
        ).aggregate(
            unique_count=Count('user', distinct=True) + 
                        Count('ip_address', distinct=True, filter=Q(user__isnull=True))
        )['unique_count'] or 0
        
        # 最后搜索时间
        last_search = RouteSearchLog.objects.filter(
            pol_cd=pol_cd,
            pod_cd=pod_cd
        ).order_by('-search_time').first()
        
        # 更新统计数据
        popular_route.search_count = total_searches
        popular_route.search_count_7d = searches_7d
        popular_route.search_count_30d = searches_30d
        popular_route.unique_users_count = unique_users
        popular_route.last_search_time = last_search.search_time if last_search else None
        
        # 计算并更新热度评分
        popular_route.calculate_popularity_score()
        popular_route.save()
        
        return popular_route
        
    except Exception as e:
        print(f"更新热门航线失败: {e}")
        return None


@api_view(['GET'])
@permission_classes([AllowAny])
def get_popular_routes(request):
    """
    获取热门航线列表
    替换前端的静态默认航线
    """
    try:
        # 获取查询参数
        limit = int(request.GET.get('limit', 10))  # 默认返回10条
        time_range = request.GET.get('time_range', 'all')  # all, 7d, 30d
        
        # 根据时间范围选择排序字段
        if time_range == '7d':
            order_field = '-search_count_7d'
        elif time_range == '30d':
            order_field = '-search_count_30d'
        else:
            order_field = '-popularity_score'
        
        # 获取热门航线
        popular_routes = PopularRoute.objects.filter(
            search_count__gt=0  # 至少被搜索过一次
        ).order_by(order_field, '-search_count')[:limit]
        
        # 格式化返回数据
        routes_data = []
        for route in popular_routes:
            routes_data.append({
                'polCd': route.pol_cd,
                'podCd': route.pod_cd,
                'name': route.route_name,
                'searchCount': route.search_count,
                'searchCount7d': route.search_count_7d,
                'searchCount30d': route.search_count_30d,
                'uniqueUsers': route.unique_users_count,
                'popularityScore': round(route.popularity_score, 1),
                'lastSearchTime': route.last_search_time.isoformat() if route.last_search_time else None
            })
        
        # 如果热门航线不足，补充一些默认的常用航线
        if len(routes_data) < limit:
            default_routes = [
                {'polCd': 'CNSHK', 'podCd': 'INMAA', 'name': '蛇口 → 金奈'},
                {'polCd': 'CNDCB', 'podCd': 'SGSIN', 'name': '大铲湾 → 新加坡'},
                {'polCd': 'CNYTN', 'podCd': 'IDJKT', 'name': '盐田 → 雅加达'},
                {'polCd': 'CNSHK', 'podCd': 'VNHPH', 'name': '蛇口 → 海防'},
                {'polCd': 'CNNAN', 'podCd': 'THBKK', 'name': '广州南沙 → 曼谷'},
                {'polCd': 'CNDCB', 'podCd': 'VNSGN', 'name': '大铲湾 → 胡志明'}
            ]
            
            # 添加不在热门列表中的默认航线
            existing_routes = set(f"{r['polCd']}-{r['podCd']}" for r in routes_data)
            for default_route in default_routes:
                route_key = f"{default_route['polCd']}-{default_route['podCd']}"
                if route_key not in existing_routes and len(routes_data) < limit:
                    routes_data.append({
                        **default_route,
                        'searchCount': 0,
                        'searchCount7d': 0,
                        'searchCount30d': 0,
                        'uniqueUsers': 0,
                        'popularityScore': 0.0,
                        'lastSearchTime': None,
                        'isDefault': True  # 标记为默认航线
                    })
        
        return Response({
            'success': True,
            'message': '获取热门航线成功',
            'data': {
                'routes': routes_data,
                'total': len(routes_data),
                'timeRange': time_range
            }
        })
        
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取热门航线失败: {str(e)}',
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_search_statistics(request):
    """
    获取搜索统计信息
    管理员可查看详细的搜索统计数据
    """
    try:
        # 时间范围
        days = int(request.GET.get('days', 30))
        start_date = timezone.now() - timedelta(days=days)
        
        # 基础统计
        total_searches = RouteSearchLog.objects.filter(search_time__gte=start_date).count()
        unique_users = RouteSearchLog.objects.filter(
            search_time__gte=start_date,
            user__isnull=False
        ).values('user').distinct().count()
        
        unique_ips = RouteSearchLog.objects.filter(
            search_time__gte=start_date
        ).values('ip_address').distinct().count()
        
        # 热门起运港
        popular_pols = RouteSearchLog.objects.filter(
            search_time__gte=start_date
        ).values('pol_cd').annotate(
            count=Count('id')
        ).order_by('-count')[:10]
        
        # 热门目的港
        popular_pods = RouteSearchLog.objects.filter(
            search_time__gte=start_date
        ).values('pod_cd').annotate(
            count=Count('id')
        ).order_by('-count')[:10]
        
        # 每日搜索趋势
        daily_stats = []
        for i in range(days):
            date = timezone.now().date() - timedelta(days=i)
            day_searches = RouteSearchLog.objects.filter(
                search_time__date=date
            ).count()
            daily_stats.append({
                'date': date.isoformat(),
                'searches': day_searches
            })
        
        return Response({
            'success': True,
            'message': '获取统计信息成功',
            'data': {
                'period': f'{days}天',
                'totalSearches': total_searches,
                'uniqueUsers': unique_users,
                'uniqueIPs': unique_ips,
                'popularPols': [
                    {
                        'polCd': item['pol_cd'], 
                        'name': get_port_name(item['pol_cd']),
                        'count': item['count']
                    } for item in popular_pols
                ],
                'popularPods': [
                    {
                        'podCd': item['pod_cd'],
                        'name': get_port_name(item['pod_cd']), 
                        'count': item['count']
                    } for item in popular_pods
                ],
                'dailyTrend': list(reversed(daily_stats))
            }
        })
        
    except Exception as e:
        return Response({
            'success': False,
            'message': f'获取统计信息失败: {str(e)}',
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)